package com.ErpCoreWeb.CommonCtrl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.ErpCoreModel.Base.AccessType;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CBaseObjectMgr;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CColumnDefaultValInView;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreWeb.Common.CVariable;
import com.ErpCoreWeb.Common.Global;

public class ShowRecordCtrl extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private CTable table = null;
	private CView view = null;
	// 受限的字段：禁止或者只读权限
	private Map<UUID, AccessType> restrictColumnAccessType = new HashMap<UUID, AccessType>();
	// 界面控件列数
	private Integer uiColCount = 2;
	// 界面控件宽度
	private Integer uiCtrlWidth = 180;
	// 外面传进来的默认值，比设置的优先
	private Map<String, String> defVal = new HashMap<String, String>();
	// 需要隐藏的字段
	private Map<String, String> hideColumn = new HashMap<String, String>();
	// 外部传进来的引用字段或枚举字段的集合
	private Map<String, CBaseObjectMgr> refBaseObjectMgr = new HashMap<String, CBaseObjectMgr>();
	// 日期型显示时间部分的字段
	private Map<String, String> showTimeColumn = new HashMap<String, String>();
	// 下拉框弹出选择方式的字段
	private Map<String, String> popupSelDialogColumn = new HashMap<String, String>();

	private CBaseObject baseObject = null;

	@Override
	public int doStartTag() throws JspException {
		try {

			JspWriter out = this.pageContext.getOut();

			if (view == null) {
				out.println("No view Found...");
				return SKIP_BODY;
			}
			
			out.println("<table cellpadding=\"0\" cellspacing=\"0\" class=\"l-table-edit\" >");
			
			    int iUICol = 0;
			    //foreach (CColumnInView civ in view.ColumnInViewMgr.GetList())
			    for(CBaseObject objCol : table.getColumnMgr().GetList())
			    {

			        //CColumn col = (CColumn)table.ColumnMgr.Find(civ.FW_Column_id);
			        CColumn col = (CColumn)objCol;
			        if (col == null)
			            continue;
			        //判断禁止权限字段
			        boolean bReadOnly = false;
			        if (restrictColumnAccessType.containsKey(col.getId()))
			        {
			            AccessType accessType = restrictColumnAccessType.get(col.getId());
			            if (accessType == AccessType.forbide)
			                continue;
			            else if (accessType == AccessType.read)
			                bReadOnly = true;
			        }
			        //
			        //判断隐藏的字段
			        boolean bHideColumn = false;
			        if (hideColumn.containsKey(col.getCode()))
			            bHideColumn = true;

			        if (col.getCode().equalsIgnoreCase("id"))
			            continue;
			        else if (col.getCode().equalsIgnoreCase("Created"))
			            continue;
			        else if (col.getCode().equalsIgnoreCase("Creator"))
			            continue;
			        else if (col.getCode().equalsIgnoreCase("Updated"))
			            continue;
			        else if (col.getCode().equalsIgnoreCase("Updator"))
			            continue;
			        
			        //字段默认值
			        CColumnDefaultValInView cdviv = view.getColumnDefaultValInViewMgr().FindByColumn(col.getId());
			        if (cdviv!=null && cdviv.getReadOnly() == true)
			            bReadOnly = true;
			        
			        //界面控件列
			        if (iUICol % uiColCount == 0)
			        	out.println("<tr>");

			        if (baseObject == null)
			        {
			            if (bHideColumn)
			            {
			                continue;
			            }
			        
			            out.println("<!--</tr>-->");
			            out.println("    <td align=\"right\" class=\"l-table-edit-td\">"+col.getName()+":</td>");
			            out.println("    <td align=\"left\" class=\"l-table-edit-td\">");
			                if (col.getColType() == ColumnType.string_type)
			                  {
			                	out.print(GetColumnDefaultVal(cdviv,col));
			                    }
			                  else if (col.getColType() == ColumnType.text_type)
			                  {
			                	  out.print(GetColumnDefaultVal(cdviv,col));
			                  }
			                  else if (col.getColType() == ColumnType.int_type)
			                  { 
			                	  out.print(GetColumnDefaultVal(cdviv,col));
			                  }
			                  else if (col.getColType() == ColumnType.long_type)
			                  { 
			                	  out.print(GetColumnDefaultVal(cdviv,col));
			                  }
			                  else if (col.getColType() == ColumnType.bool_type)
			                  {
			                      String defval = GetColumnDefaultVal(cdviv, col).toLowerCase();
			                      if (defval.equalsIgnoreCase("1") || defval.equalsIgnoreCase("true"))
			                    	  out.print("是");
			                      else
			                    	  out.print("否");
			                  }
			                  else if (col.getColType() == ColumnType.numeric_type)
			                  {
			                	  out.print(GetColumnDefaultVal(cdviv,col));
			                  }
			                  else if (col.getColType() == ColumnType.guid_type)
			                  { 
			                	  out.print(GetColumnDefaultVal(cdviv,col)) ;
			                  }
			                  else if (col.getColType() == ColumnType.datetime_type)
			                  { 
			                	  out.print(GetColumnDefaultVal(cdviv,col)) ;
			                  }
			                  else if (col.getColType() == ColumnType.ref_type)
			                  {
			                	  out.print( GetColumnRefDefaultVal(cdviv,col));                      
			                  }
			                  else if (col.getColType() == ColumnType.enum_type)
			                  {
			                	  out.print(GetColumnDefaultVal(cdviv,col));
			                  }
			                  else if (col.getColType() == ColumnType.object_type)
			                  {
			                  }
			                  else if (col.getColType() == ColumnType.path_type)
			                  {
			                  } 
			                out.println("</td>");
			                out.println("<td align=\"left\" style=\"width:50px\"></td>");
			                out.println("<!--</tr>-->");
			        }
			        else
			        {
			            if (bHideColumn)
			            {
			                continue;
			            }
			        
			                    
			            out.println("<!--</tr>-->");
			            out.println("<td align=\"right\" class=\"l-table-edit-td\">"+col.getName()+":</td>");
			            out.println("<td align=\"left\" class=\"l-table-edit-td\">");
			                if (col.getColType() == ColumnType.string_type)
			                  { 
			                	out.print(baseObject.GetColValue(col));
			                }
			                  else if (col.getColType() == ColumnType.text_type)
			                  {
			                	  out.print(baseObject.GetColValue(col));
			                }
			                  else if (col.getColType() == ColumnType.int_type)
			                  { 
			                	  out.print(baseObject.GetColValue(col));
			                  }
			                  else if (col.getColType() == ColumnType.long_type)
			                  { 
			                	  out.print(baseObject.GetColValue(col));
			                  }
			                  else if (col.getColType() == ColumnType.bool_type)
			                  { 
			                  if((Boolean)baseObject.GetColValue(col))
			                	  out.print("是");
			                     else
			                    	 out.print("否");
			                    
			                  }
			                  else if (col.getColType() == ColumnType.numeric_type)
			                  { 
			                	  out.print(baseObject.GetColValue(col));
			                  }
			                  else if (col.getColType() == ColumnType.guid_type)
			                  { 
			                	  out.print(baseObject.GetColValue(col));
			                  }
			                  else if (col.getColType() == ColumnType.datetime_type)
			                  {
			                      Date dtime = (Date)baseObject.GetColValue(col);
			              		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			            		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
			                      if (showTimeColumn.containsKey(col.getCode()))
			                    	  out.print(format2.format(dtime));
			                      else
			                    	  out.print(format.format(dtime));
			                  }
			                  else if (col.getColType() == ColumnType.ref_type)
			                  {
			                	  out.print(baseObject.GetRefShowColVal(col));
			                  
			                  }
			                  else if (col.getColType() == ColumnType.enum_type)
			                  {
			                      
			                	  out.print(baseObject.GetColValue(col));
			                    
			                  }
			                  else if (col.getColType() == ColumnType.object_type)
			                  {
			                  }
			                  else if (col.getColType() == ColumnType.path_type)
			                  {
			                      Object objVal = baseObject.GetColValue(col);
			                      if (objVal != null)
			                      {
			                          String sVal = objVal.toString();
			                          String[] arr = sVal.split("\\|");
			                          String sUrl = "";
			                          if (arr.length ==2)
			                          {
			                              sUrl = arr[0];
			                              ResourceBundle rb=ResourceBundle.getBundle("config");//WEB-INF/config.properties        
			                              String sPath = this.pageContext.getServletContext().getRealPath(rb.getString("VirtualDir"));
			                              sPath = col.getUploadPath().toLowerCase().replace(sPath.toLowerCase(), rb.getString("VirtualDir"));
			                              sPath = sPath.replace('\\', '/');
			                              if(sPath.length()>0 && !sPath.endsWith("/"))
			                                  sPath += '/';
			                              
			                              boolean bIsImg = false;
			                              int idx = sUrl.lastIndexOf('.');
			                              if (idx > -1)
			                              {
			                                  String sExt = sUrl.substring(idx);
			                                  sExt = sExt.toLowerCase();
			                                  if (sExt.equalsIgnoreCase(".jpg") || sExt.equalsIgnoreCase(".png") || sExt.equalsIgnoreCase(".bmp") || sExt.equalsIgnoreCase(".jpeg") || sExt.equalsIgnoreCase(".gif"))
			                                      bIsImg = true;
			                              }
			                              sUrl = sPath + sUrl;

			                              String sContent = "";
			                              if (bIsImg)
			                              {
			                                  sContent = String.format("<img src='%s' style='width:100px;height:120px;'>", sUrl);
			                              }
			                              else
			                              {
			                                  sContent = String.format("<a href='%s'>%s</a>", sUrl, arr[1]);
			                              }

			                              out.print(sContent);
			                          }
			                      }
			                  } 
			                out.println("</td>");
			                out.println("<td align=\"left\" style=\"width:50px\"></td>");
			                out.println("<!--</tr>-->");
			        }
			        iUICol++;
			    }
			
			    
			    out.println("</table>");
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public void release() {
		super.release();
		this.baseObject = null;
	}


    public String GetColumnDefaultVal(CColumnDefaultValInView cdviv, CColumn col)
    {
        //外面传进来的默认值，比设置的优先
        if (defVal.containsKey(col.getCode()))
        {
            return defVal.get(col.getCode());
        }
        //

        if (cdviv == null || cdviv.getDefaultVal().trim().length()==0)
            return "";
        //变量
        if (cdviv.getDefaultVal().length() > 2 && cdviv.getDefaultVal().startsWith("[") && cdviv.getDefaultVal().endsWith("]"))
        {
            CVariable Variable = new CVariable((HttpServletRequest) this.pageContext.getServletContext());
            return Variable.GetVarValue(cdviv.getDefaultVal());
        }
        //sql语句
        else if (cdviv.getDefaultVal().length() > 4 && cdviv.getDefaultVal().substring(0, 4).equalsIgnoreCase("sql:"))
        {
            String sSql = cdviv.getDefaultVal().substring(4);
            Object obj = Global.GetCtx(this.pageContext.getServletContext()).getMainDB().GetSingle(sSql);
            if (obj == null)
                return "";
            else
                return obj.toString();
        }
        //常量
        else
            return cdviv.getDefaultVal();
    }

    public String GetColumnRefDefaultVal(CColumnDefaultValInView cdviv, CColumn col)
    {
        CTable RefTable = (CTable)Global.GetCtx(this.pageContext.getServletContext()).getTableMgr().Find(col.getRefTable());
        CBaseObjectMgr BaseObjectMgr = Global.GetCtx(this.pageContext.getServletContext()).FindBaseObjectMgrCache(RefTable.getCode(), Util.GetEmptyUUID());
        if (BaseObjectMgr == null)
        {
            BaseObjectMgr = new CBaseObjectMgr();
            BaseObjectMgr.TbCode = RefTable.getCode();
            BaseObjectMgr.Ctx = Global.GetCtx(this.pageContext.getServletContext());
        }

        CColumn RefCol = (CColumn)RefTable.getColumnMgr().Find(col.getRefCol());
        CColumn RefShowCol = (CColumn)RefTable.getColumnMgr().Find(col.getRefShowCol());
        List<CBaseObject> lstObjRef = BaseObjectMgr.GetList();
        String defval = GetColumnDefaultVal(cdviv, col).toString();
        for (CBaseObject objRef : lstObjRef)
        {
            String val = objRef.GetColValue(RefCol).toString();
            if (defval == val)
            {
                return objRef.GetColValue(RefShowCol).toString();
            }
        }
        return "";
    }
    

	// getter and setters
	public CBaseObject getBaseObject() {
		return baseObject;
	}

	public void setBaseObject(CBaseObject BaseObject) {
		this.baseObject = BaseObject;
	}

	public CTable getTable() {
		return table;
	}

	public void setTable(CTable Table) {
		this.table = Table;
	}

	public CView getView() {
		return view;
	}

	public void setView(CView View) {
		this.view = View;
	}
	

	public Map<String, String> getPopupSelDialogColumn() {
		return popupSelDialogColumn;
	}

	public void setPopupSelDialogColumn(Map<String, String> PopupSelDialogColumn) {
		this.popupSelDialogColumn = PopupSelDialogColumn;
	}
	public Map<String, String> getShowTimeColumn() {
		return showTimeColumn;
	}

	public void setShowTimeColumn(Map<String, String> ShowTimeColumn) {
		this.showTimeColumn = ShowTimeColumn;
	}
	public Map<String, CBaseObjectMgr> getRefBaseObjectMgr() {
		return refBaseObjectMgr;
	}

	public void setRefBaseObjectMgr(Map<String, CBaseObjectMgr> RefBaseObjectMgr) {
		this.refBaseObjectMgr = RefBaseObjectMgr;
	}
	public Map<String, String> getHideColumn() {
		return hideColumn;
	}

	public void setHideColumn(Map<String, String> HideColumn) {
		this.hideColumn = HideColumn;
	}
	public Map<String, String> getDefVal() {
		return defVal;
	}

	public void setDefVal(Map<String, String> DefVal) {
		this.defVal = DefVal;
	}
	public Integer getUiCtrlWidth() {
		return uiCtrlWidth;
	}

	public void setUiCtrlWidth(Integer UICtrlWidth) {
		this.uiCtrlWidth = UICtrlWidth;
	}
	public int getUiColCount() {
		return uiColCount;
	}

	public void setUiColCount(Integer UIColCount) {
		this.uiColCount = UIColCount;
	}
	public Map<UUID, AccessType> getRestrictColumnAccessType() {
		return restrictColumnAccessType;
	}

	public void setRestrictColumnAccessType(Map<UUID, AccessType> RestrictColumnAccessType) {
		this.restrictColumnAccessType = RestrictColumnAccessType;
	}
}
